package com.example.boot02.controller;

import com.example.boot02.entity.User;
import com.example.boot02.util.DBUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user) {
        System.out.println("user = " + user);/*soutp快捷键输出对象*/
        try (Connection conn = DBUtil.getConnection()){
            String spl = "insert into user values(null,?,?,?)";
            /*PreparedStatement 预处理语句*/
            PreparedStatement ps = conn.prepareStatement(spl);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getNickname());
            ps.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "注册成功";
    }
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user) {
        System.out.println("user = " + user);
        try (Connection conn = DBUtil.getConnection()){
            String sql = "select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            /*执行查询*/
            ResultSet rs = ps.executeQuery();
            //判断是否查询到了数据
            if (rs.next()){//查询到了
                //得到查询到的密码
                String pw = rs.getString(1);
                //判断查询到的密码和用户输入的密码是否一致
                // pw代表数据库里面的密码  user.getPassword()得到用户输入的密码
                if (pw.equals(user.getPassword())){
                    return "登录成功!";
                }
                return "密码错误";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名不存在";
    }
}
